﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DNA.Mvc.jQuery
{
    /// <summary>
    /// Defines the base container class contains DataBindableComponent
    /// </summary>
    /// <typeparam name="TModel"></typeparam>
    /// <typeparam name="TComponentItem"></typeparam>
    public abstract class DataBindableContainer<TModel, TComponentItem> : ContainerViewComponent<TComponentItem>
        where TComponentItem : ViewComponent
        where TModel : class
    {
        private HtmlTemplate<TModel> itemTemplate = new HtmlTemplate<TModel>();

        /// <summary>
        /// Gets/Sets the data model
        /// </summary>
        public IEnumerable<TModel> Model { get; set; }

        /// <summary>
        /// Gets/Sets the Server ItemTemplate for all childen items.
        /// </summary>
        public HtmlTemplate<TModel> ItemTemplate
        {
            get { return itemTemplate; }
            set { itemTemplate = value; }
        }

        public override void RenderContent(System.Web.UI.HtmlTextWriter writer)
        {
            if (Model != null)
            {
                foreach (var dataItem in Model)
                {
                    if (!ItemTemplate.IsEmpty)
                        ItemTemplate.WriteTo(dataItem, writer);
                }
            }
            else
            {
                foreach (var item in InnerItems)
                    item.Render(writer);
            }
        }
    }
}
